package br.net.atasacramental.menu.business;
import br.net.atasacramental.menu.model.Menu;
import br.net.atasacramental.menu.model.ItemMenu;
import br.net.atasacramental.usuario.business.UsuarioBLL;
import br.net.atasacramental.usuario.model.Usuario;
import br.net.atasacramental.menu.dao.MenuDAO;

import java.util.ArrayList;
import java.util.List;

import under.wsl.service.Service;
/**
 * @author alexandre.araujo
 */
public class MenuBLL{
    private MenuDAO dao = null;
    public MenuBLL() {
        this.dao = new MenuDAO();
    }
    @Service(cache=true)
    public List<Menu> get(){
        return this.dao.get();
    }
    @Service()
    public Menu getByIdMenu(int idMenu) {
        return this.dao.getByIdMenu(idMenu);
    }
    @Service()
    public List<Menu> getByLabel(String label) {
        return this.dao.getByLabel(label);
    }
    @Service()
    public List<Menu> getByOrdem(int ordem) {
        return this.dao.getByOrdem(ordem);
    }
    @Service(remove={"MenuBLL.get"})   
    public int insert(Menu m){    
        if(this.dao.insert(m)){            
            return m.getIdMenu();
        }
        return 0;
    }
    @Service(remove={"MenuBLL.get"})
    public boolean update(Menu m){
        return this.dao.update(m);
    }
    @Service(remove={"MenuBLL.get"})
    public boolean delete(Menu m){
         return this.dao.delete(m);
    }  
    @Service()
    public List<Menu> getMenusByLoginUsuario(String login){
            UsuarioBLL usdbl = new UsuarioBLL();
            Usuario user =  usdbl.getByLogin(login);
            if(user!=null){
            	return this.getMenusByIdGrupo(user.getIdGrupo());
            }
            return this.getMenusByIdGrupo(0);
    }
    @Service(cache=false)
    public List<Menu> getMenusByIdGrupo(int idGrupo){
    	List<Menu> menus = this.dao.get();      
        List<Menu> menusTMP = new ArrayList<Menu>();
        ItemMenuBLL midbl = new ItemMenuBLL();
        int tmm = menus.size();
        for(int i=0;i<tmm;i++){
        	//PEGA TODOS OS ITENS DE TODOS MENUS PARA TESTE
        	//List<MenuItem> itensTMP = midbl.getByIdMenu(menus.get(i).getIdMenu());       	
        	List<ItemMenu> itensTMP = midbl.getItensByIdGrupoIdMenu(idGrupo, menus.get(i).getIdMenu());
        	if(itensTMP.size()>0){
        		/*SO PREENCHE O MENU SE HOUVER ITENS*/
        		menus.get(i).setChildren(itensTMP);
        		menusTMP.add(menus.get(i));
        	}
        }
        return menusTMP;
    }
}
